package com.dnb.webmash.playmaker.server;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.dnb.webmash.playmaker.shared.MediaType;
import com.dnb.webmash.playmaker.shared.PlaylistItem;

public class PlaylistFromMediaTypes {
	
	/*
	 * Helper method to add media items
	 */
	public static ArrayList<PlaylistItem> addMediaItems(String page, MediaType mediaType, String requestedURL) {
		ArrayList<PlaylistItem> mediaItems = new ArrayList<PlaylistItem>();
		Pattern pattern; Matcher matcher;
		ArrayList<String> patternsForIDs = new ArrayList<String>(mediaType.getMediaIDPats());
		if (patternsForIDs !=null){
			for (int i = 0; i < patternsForIDs.size(); i++){
				pattern = Pattern.compile(patternsForIDs.get(i));
				matcher = pattern.matcher(page);				
				while (matcher.find()) {
					String found = matcher.group(1);
					String sourceURL = mediaType.getSourceURL();								
					
					//TODO this could be used to solve the local hosted videos when going to youtube.com or other hosts
					if ((sourceURL==null) || (sourceURL.isEmpty())){//if the mediatype has no sourceURL then it must be hosted at the requested url
						if (!ServerFieldVerifier.isValidURL(found))//if the media_id doesnt specify a sourceurl
							sourceURL = ServerFieldVerifier.trimToLastSlash(requestedURL);						
					}
					
					PlaylistItem f = new PlaylistItem(sourceURL,found);//found = MyURL snip = the video_id				
					f.setPlayable(true);// tell playmaker to put this in the master playlist
					f.setMediatype(mediaType.getName());//contains the playertype information
					f.setPlayerType(mediaType.getPlayerType());
					if (!mediaItems.isEmpty()){
						if (!mediaItems.contains(f)) mediaItems.add(f); //add this media item if not already there //TODO INFIX
					}
					else {
						mediaItems.add(f);
					}
				}	
			}
		}
		if (!mediaItems.isEmpty()) return mediaItems;
		else return new ArrayList<PlaylistItem>();//empty
	}
}
